#-*-coding: UTF-8 -*-
'''
#ref1:https://www.jb51.net/article/145022.htm       http上传file
#ref2:https://www.jianshu.com/p/069bbe060826        http上传file
#ref3:https://github.com/ipfs/py-ipfs-http-client   ipfs add file
#ref4:https://github.com/stlehmann/Flask-MQTT       mqtt
'''
from web3 import Web3
from web3.middleware import geth_poa_middleware
import time
import os
from werkzeug.utils import secure_filename
from flask import Flask, render_template, jsonify, request, send_from_directory, abort
import ipfshttpclient
import socket
from flask_socketio import SocketIO
from flask_bootstrap import Bootstrap

app = Flask(__name__)
socketio = SocketIO(app)

UPLOAD_FOLDER = 'upload'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
basedir = os.path.abspath(os.path.dirname(__file__))
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'JPG', 'PNG', 'pdf', 'PDF', 'mp4', 'MP4', 'mp3', 'MP3', 'AVI', 'avi', 'WMV', 'wmv'])

# HTTPProvider:
ethuri = 'http://localhost:8544'
w3 = Web3(Web3.HTTPProvider(ethuri))
#w3.isConnected()
w3.middleware_onion.inject(geth_poa_middleware, layer=0) 
if w3.isConnected():   
    print('connected to ehterum node at ' + ethuri)
    print(w3.clientVersion)
else:
    print('unable to connect to ethereum node at ' + ethuri)

# 用于判断文件后缀
def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS

def get_host_ip():
    """
    查询本机ip地址
    :return: ip
    """
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(('8.8.8.8', 80))
        ip = s.getsockname()[0]
    finally:
        s.close()
    return ip

@app.route('/')
def index():
    return 'hello world'
	
@app.route('/file', methods=['POST'], strict_slashes=False)
def fileupload():
    file_dir = os.path.join(basedir, app.config['UPLOAD_FOLDER'])
    if not os.path.exists(file_dir):
        os.makedirs(file_dir)
    print(request.files)
    #print(request.data)
    f = request.files['fileup']
    if f and allowed_file(f.filename):
        fname = secure_filename(f.filename)
        print('filename:')
        print(fname)
        filename = fname.rsplit('.', 1)[0]  # 获取文件名
        print(filename)
        ext = fname.rsplit('.', 1)[1]  # 获取文件后缀
        unix_time = int(time.time())
        timeArray = time.localtime(unix_time)
        otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
        new_filename = filename +'_'+ str(unix_time) + '.' + ext  # 修改了上传的文件名
        print('new_filename:')
        print(new_filename)
        f.save(os.path.join(file_dir, new_filename))  # 保存文件到upload目录
        #filehash = 0x1234
        ipfsclient = ipfshttpclient.connect()
        #ipfsclient = ipfshttpclient.connect(ipfsapi)
        filehash = ipfsclient.add(file_dir+'/'+new_filename)['Hash']
        #filehash = ipfsclient.add('./upload/new_filename')['Hash']
        #filehashstr = filehash.encode('utf-8')
        #print(filehashstr)
        #print(type(filehash))
        print('ipfsHash:'+filehash)
        fileip = get_host_ip()
        block_dict = {"filename": new_filename, "filehash": filehash, "fileip": fileip, "uptime": otherStyleTime}  
        blockstr = '0x' + str(block_dict).encode('utf-8').hex()
        print(blockstr)
        accounts = w3.eth.accounts
        if len(accounts)>1:
            user1 = w3.eth.accounts[1]
        else:
            user1 = w3.geth.personal.new_account("1234")
            print('create new account:'+user1)
        print('use the second account:'+user1)
        user0 = w3.eth.coinbase
        txpy = w3.eth.send_transaction({'to': user1, 'from': user0, 'value': w3.toWei(0.01, 'ether'),'data':blockstr})
        #print('transaction result:'+ txpy.decode('utf-8'))
        blockn = w3.eth.get_block('latest')
        json_dict = {"filename": new_filename, "filehash": filehash, "fileip": fileip, "uptime": otherStyleTime,"PossibleBlockNumber":blockn.number+1}  
		
        print('handle_publish:')
        print(str(json_dict))
        print(type(json_dict))
        return jsonify(json_dict)
    else:
        return jsonify({"error": 1001, "msg": "上传失败"})
		
if __name__ == '__main__':
    socketio.run(app, host='0.0.0.0', port=5000, use_reloader=True, debug=True)
